package com.example.fish.ws;

import com.example.fish.config.GetHttpSessionConfig;
import com.example.fish.pojo.User;
import com.example.fish.service.WebSocketService;
import com.example.fish.service.ex.SendMessageException;
import com.example.fish.utils.MessageUtils;
import com.example.fish.utils.SensitiveWordFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/***
 * websocket实现类
 */
@ServerEndpoint(value = "/chat/{targetid}",configurator = GetHttpSessionConfig.class)
@Component
@Controller
public class ChatEndpoint  {
    /***
     * 注入service为空的原因：spring管理的是单例，但是socket为多例
     */
    @Resource
    private SensitiveWordFilter sensitiveWordFilter;
    private static WebSocketService webSocketService;
    @Autowired
    public  void  setWebSocketService(WebSocketService webSocketService){
        ChatEndpoint.webSocketService = webSocketService;
    }
    //    保存每一个客户端
    private static final Map<String,Session> sessionMap = new ConcurrentHashMap<>();

    private  HttpSession httpSession;
    private Integer targetid;
//    private Integer fromuserid;
    private User user;

    // WebSocket连接建立时被调用
    @OnOpen
    public void onOpen(Session session, EndpointConfig config,@PathParam("targetid") Integer targetid) {
        this.targetid = targetid;
//        this.fromuserid = fromuserid;
//        System.out.println("from!!"+fromuserid);
        this.httpSession =(HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.user =(User) httpSession.getAttribute("user");
//        将用户id作为key存储到sessionMap
        sessionMap.put(user.getUserid().toString(),session);
//        处理未读消息
        webSocketService.deleteOfflineMessage(user.getUserid(),targetid);

    }
    @OnMessage
    public void onMessage(String message) throws IOException{
        //接收到消息触发
            sendMessage(message,targetid.toString());
    }
    /***
     * 发送消息/保存离线消息
     */
    private void sendMessage(String message,String target) throws IOException{
        try {
//            Set<Map.Entry<String, Session>> entries = sessionMap.entrySet();
            Session session = sessionMap.get(target);
                    if(session!=null){
//                        Session session = entry.getValue();
                        String message1 = MessageUtils.getMessage(message, user.getUserid(), targetid);
                        session.getBasicRemote().sendText(message1);
                        webSocketService.saveMessage(user.getUserid(), Integer.parseInt(target),message);
                    }else{
                        System.out.println("对方不在线");
                        webSocketService.saveOfflineMessage(user.getUserid(),Integer.parseInt(target),message);
                    }
        }catch (Exception e){
            throw new SendMessageException("发消息发生错误");
        }
    }



    /***
     * 断开websocket链接时，被调用
     */
    @OnClose
    public void onClose(Session session) {
//        System.out.println("close : "+session.getId());
//        sessionMap.remove(user.getUserid().toString());
        System.out.println("关闭的id："+session.getId());
        sessionMap.remove(session.getId());
    }

    @OnError
    public void onError(Session session, Throwable error) {
//        System.out.println("发生错误了"+error.getMessage());
        System.out.println("error:::"+error.getMessage());
    }

}
